from Crypto.PublicKey import RSA
from Crypto.Hash import SHA256, SHA1
import base64
import time
from urllib.parse import urlencode
from .request.alipay_trade_app_pay_request import AliPayTradeAppPayRequest

class AopClient(object):
    """Aop Client"""

    # 应用ID
    app_id = None

    # 私钥文件路径
    rsa_private_key_path = None

    # 私钥值
    rsa_private_key = None

    # 网关
    gateway_url = "https://openapi.alipaytmp.com/gateway.do"

    # 返回数据格式
    format = 'json'

    # apiVersion
    api_version = '1.0'

    # Charset
    post_charset = 'UTF-8'

    # 使用文件读取文件格式，请只传递该值
    alipay_public_key = None

    # 使用读取字符串格式，请只传递该值
    alipay_rsa_public_key = None

    debug_info = False

    file_charset = 'UTF-8'

    __RESPONSE_SUFFIX = "_response"

    __ERR_RESPONSE = "error_response"

    __SIGN_NODE_NAME = "sign"

    __ENCRYPT_XML_NODE_NAME = "response_encrypted"

    need_encrypt = False

    sign_type = 'RSA'

    encrypt_key = None

    encrypt_type = 'AES'

    alipay_sdk_version = 'alipaytmp-sdk-php-20161101'

    def generate_sign(self, sign_type='RSA', params={}):  # need sign
        return self.sign(self.get_sign_content(params), sign_type=sign_type)

    def get_sign_content(self, params):
        keys = sorted(list(params.keys()))
        s = ''
        parts = []
        for k in keys:
            part = k + '=' + params[k]
            parts.append(part)
        return '&'.join(parts)

    def sign(self, data, sign_type='RSA'):  # need check_empty
        if not self.rsa_private_key_path:
            pri_key = self.rsa_private_key
            res = "-----BEGIN RSA PRIVATE KEY-----\n" + pri_key + "\n-----END RSA PRIVATE KEY-----"
        else:
            with open(self.rsa_private_key_path) as f:
                res = RSA.importKey(f.read())

        if sign_type == 'RSA2':
            shaer = SHA256.new(res.encode())
        else:
            shaer = SHA1.new(res.encode())
        sign = base64.b64encode(shaer.update(data.encode()))
        return sign

    def sdk_execute(self, request: AliPayTradeAppPayRequest):
        params = {
            'app_id': self.app_id,
            'method': request.api_method_name,
            'format': self.format,
            'sign_type': self.sign_type,
            'timestamp': time.strftime('%Y-%m-%d %H:%M:%S'),
            'alipay_sdk': self.alipay_sdk_version,
            'charset': self.post_charset,
        }
        version = request.api_version
        params['version'] = version
        params['notify_url'] = request.notify_url

        mydict = request.api_paras
        params['biz_content'] = mydict['biz_content']
        params['sign'] = self.generate_sign(sign_type=self.sign_type, params=params)
        return urlencode(params)

    def setup_charsets(self, request):
        pass
